package com.example.demo.testOne;

import com.example.demo.pojo.dto.Student;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description stream分组求和
 *
 * @author lilinchun
 * @date 2023/12/18
 */
public class demo20 {


    public static void main(String[] args) {
        List<Student> students = Stream.of(
                Student.builder().name("小张").age(16).clazz("高一1班").course("历史").score(88).build(),
                Student.builder().name("小李").age(16).clazz("高一3班").course("数学").score(12).build(),
                Student.builder().name("小王").age(17).clazz("高二1班").course("地理").score(44).build(),
                Student.builder().name("小红").age(18).clazz("高二1班").course("物理").score(67).build(),
                Student.builder().name("李华").age(15).clazz("高二2班").course("数学").score(99).build(),
                Student.builder().name("小潘").age(19).clazz("高三4班").course("英语").score(100).build(),
                Student.builder().name("小聂").age(20).clazz("高三4班").course("物理").score(32).build()
        ).collect(Collectors.toList());

        // 分组计数
        Map<String, Long> groupCount = students.stream()
                .collect(Collectors.groupingBy(Student::getCourse, Collectors.counting()));

        System.out.println(groupCount.toString());


        // 分组求和
        Map<String, Integer> groupSum = students.stream()
                .collect(Collectors.groupingBy(Student::getCourse, Collectors.summingInt(Student::getScore)));

        System.out.println(groupSum);

        // 分组求平均
        Map<String, Double> groupAverage = students.stream()
                .collect(Collectors.groupingBy(Student::getCourse, Collectors.averagingInt(Student::getScore)));

        System.out.println(groupAverage);


        // 同组最小值
        Map<String, Student> groupMin2 = students.stream()
                .collect(Collectors.groupingBy(Student::getCourse,
                        Collectors.collectingAndThen(Collectors.minBy(Comparator.comparing(Student::getCourse)), op ->op.orElse(null))));

        System.out.println(groupAverage);


        // 同组最大值
        Map<String, Optional<Student>> groupMax = students.stream()
                .collect(Collectors.groupingBy(Student::getCourse,Collectors.maxBy(Comparator.comparing(Student::getCourse))));
        System.out.println(groupMax);

    }
}
